<template>
  <el-container style="min-height: 100vh">
    <el-aside width="260px" style="background: #fff; box-shadow: 2px 0 8px #f0f1f2">
      <div style="padding: 16px; text-align: center; font-weight: bold; font-size: 18px">历史会话</div>
      <el-button type="primary" style="margin: 16px 0; width: 90%" @click="createChat">新建会话</el-button>
      <el-menu :default-active="String(selectedChatId)" @select="handleSelectChat" style="border: none">
        <el-menu-item v-for="chat in chatList" :key="chat.id" :index="String(chat.id)">
          {{ chat.title }}
        </el-menu-item>
      </el-menu>
      <el-button type="danger" icon="el-icon-switch-button" style="margin: 16px; width: 90%" @click="logout" plain>退出登录</el-button>
    </el-aside>
    <el-container>
      <el-header style="background: #fff; box-shadow: 0 2px 8px #f0f1f2; padding: 15px; font-size: 20px; font-weight: bold">
        智能问答助手
      </el-header>
      <el-main style="background: #f0f2f5; padding: 24px">
        <div v-if="selectedChatId">
          <el-scrollbar height="400px">
            <div v-for="(item, idx) in messageList" :key="idx" style="margin-bottom: 16px;">
              <div style="text-align: right;">
                <div style="display: inline-block; background: #aee1f9; color: #333; border-radius: 16px; padding: 8px 16px; margin-bottom: 4px;">
                  你：{{ item.question }}
                  <template v-if="item.imageUrl">
                    <img :src="item.imageUrl" style="max-width: 120px; max-height: 80px; margin-left: 8px; vertical-align: middle;" />
                  </template>
                </div>
              </div>
              <div style="text-align: left;">
                <div style="display: inline-block; background: #fff; color: #333; border-radius: 16px; padding: 8px 16px;">
                  助手：{{ item.answer }}
                </div>
              </div>
            </div>
          </el-scrollbar>
          <div style="display: flex; margin-top: 24px; align-items: flex-end;">
            <el-input v-model="question" type="textarea" :rows="2" placeholder="请输入你的问题..." style="margin-right: 8px" />
            <el-upload :show-file-list="false" :before-upload="beforeUpload">
              <el-button icon="el-icon-picture" style="margin-right: 8px">图片</el-button>
            </el-upload>
            <el-button type="primary" @click="handleSend" :loading="loading">发送</el-button>
          </div>
          <div v-if="image" style="margin-top: 8px; color: #888; font-size: 13px;">已选择图片：{{ image.name }}</div>
        </div>
        <div v-else style="text-align:center; color:#888; margin-top:100px;">请选择或新建一个会话</div>
      </el-main>
    </el-container>
  </el-container>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import axios from 'axios';

const router = useRouter();
const userId = localStorage.getItem('userId');
const chatList = ref([]); // 会话列表
const selectedChatId = ref(null); // 当前选中会话id
const messageList = ref([]); // 当前会话消息
const question = ref('');
const loading = ref(false);
const image = ref(null);

const fetchChatList = async () => {
  if (!userId) return;
  try {
    const res = await axios.get(`/api/chat/list/${userId}`);
    chatList.value = res.data;
    if (chatList.value.length && !selectedChatId.value) {
      selectedChatId.value = chatList.value[0].id;
      fetchMessageList(selectedChatId.value);
    }
  } catch (e) {
    ElMessage.error('会话列表加载失败');
  }
};

const fetchMessageList = async (chatId) => {
  try {
    const res = await axios.get(`/api/chat/history/${chatId}`);
    messageList.value = res.data;
  } catch (e) {
    ElMessage.error('消息加载失败');
  }
};

const handleSelectChat = (chatId) => {
  selectedChatId.value = Number(chatId);
  fetchMessageList(selectedChatId.value);
};

const beforeUpload = (file) => {
  image.value = file;
  return false;
};

const handleSend = async () => {
  if (!question.value && !image.value) return ElMessage.warning('请输入问题或选择图片');
  if (!selectedChatId.value) return ElMessage.warning('请先选择会话');
  loading.value = true;
  try {
    const formData = new FormData();
    formData.append('data', JSON.stringify({
      chatId: selectedChatId.value,
      userId,
      question: question.value
    }));
    if (image.value) formData.append('image', image.value);
    const res = await axios.post('/api/chat/send', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    });
    messageList.value.push(res.data);
    question.value = '';
    image.value = null;
  } catch (e) {
    ElMessage.error('发送失败');
  }
  loading.value = false;
};

const createChat = async () => {
  const title = prompt('请输入会话标题');
  if (!title) return;
  try {
    const res = await axios.post('/api/chat/create', { userId, title });
    chatList.value.unshift(res.data);
    selectedChatId.value = res.data.id;
    messageList.value = [];
  } catch (e) {
    ElMessage.error('新建会话失败');
  }
};

const logout = () => {
  localStorage.removeItem('userId');
  router.push('/login');
};

onMounted(() => {
  if (!userId) {
    router.push('/login');
    return;
  }
  fetchChatList();
});
</script>